import { BaseModel } from './BaseModel.js';

export class UserModel extends BaseModel {
    constructor() {
        super();
        this.tableName = 'users';
    }

    // 查找所有用户（支持搜索和分页）
    async findAll({ search, limit, offset }) {
        try {
            const whereConditions = [];
            const params = [];
            
            if (search) {
                whereConditions.push('(username LIKE ? OR email LIKE ? OR full_name LIKE ?)');
                const searchTerm = `%${search}%`;
                params.push(searchTerm, searchTerm, searchTerm);
            }
            
            const whereClause = whereConditions.length > 0 ? whereConditions.join(' AND ') : '1=1';
            
            return await super.findAll(this.tableName, {
                select: 'id, username, email, full_name, phone, role, status, created_at, updated_at, last_login_at',
                where: whereClause,
                whereParams: [...params, limit, offset],
                orderBy: 'created_at DESC',
                limit,
                offset
            });
        } catch (error) {
            throw new Error(`Database query failed: ${error.message}`);
        }
    }

    // 统计用户数量
    async count({ search }) {
        try {
            let query = `SELECT COUNT(*) as total FROM users WHERE 1=1`;
            const params = [];
            
            if (search) {
                query += ` AND (username LIKE ? OR email LIKE ? OR full_name LIKE ?)`;
                const searchTerm = `%${search}%`;
                params.push(searchTerm, searchTerm, searchTerm);
            }
            
            const [rows] = await this.pool.execute(query, params);
            return rows[0].total;
        } catch (error) {
            throw new Error(`Database count failed: ${error.message}`);
        }
    }

    // 根据ID查找用户
    async findById(id) {
        try {
            return await super.findById(this.tableName, id, 
                'id, username, email, full_name, phone, role, status, created_at, updated_at, last_login_at'
            );
        } catch (error) {
            throw new Error(`Database query failed: ${error.message}`);
        }
    }

    // 根据用户名查找用户（包含密码，用于登录）
    async findByUsername(username) {
        try {
            return await super.findOne(this.tableName, { username }, 
                'id, username, email, full_name, phone, role, status, password, created_at, updated_at, last_login_at'
            );
        } catch (error) {
            throw new Error(`Database query failed: ${error.message}`);
        }
    }

    // 根据用户名或邮箱查找用户
    async findByUsernameOrEmail(username, email) {
        try {
            const query = `
                SELECT id, username, email 
                FROM users 
                WHERE username = ? OR email = ?
            `;
            
            const [rows] = await this.pool.execute(query, [username, email]);
            return rows[0] || null;
        } catch (error) {
            throw new Error(`Database query failed: ${error.message}`);
        }
    }

    // 根据用户名或邮箱查找用户（排除指定ID）
    async findByUsernameOrEmailExcludeId(username, email, excludeId) {
        try {
            const query = `
                SELECT id, username, email 
                FROM users 
                WHERE (username = ? OR email = ?) AND id != ?
            `;
            
            const [rows] = await this.pool.execute(query, [username, email, excludeId]);
            return rows[0] || null;
        } catch (error) {
            throw new Error(`Database query failed: ${error.message}`);
        }
    }

    // 创建新用户
    async create(userData) {
        try {
            const createData = {
                username: userData.username,
                email: userData.email,
                password: userData.password,
                full_name: userData.full_name || null,
                phone: userData.phone || null,
                role: userData.role || 'user',
                status: userData.status || 'active'
            };
            
            const result = await super.create(this.tableName, createData);
            
            // 返回创建的用户（不包含密码）
            return await this.findById(result.insertId);
        } catch (error) {
            throw new Error(`Database insert failed: ${error.message}`);
        }
    }

    // 更新用户
    async update(id, updateData) {
        try {
            const allowedFields = ['username', 'email', 'password', 'full_name', 'phone', 'role', 'status'];
            const cleanData = {};
            
            Object.keys(updateData).forEach(key => {
                if (allowedFields.includes(key) && updateData[key] !== undefined) {
                    cleanData[key] = updateData[key];
                }
            });
            
            if (Object.keys(cleanData).length === 0) {
                throw new Error('No valid fields to update');
            }
            
            const result = await super.update(this.tableName, id, cleanData);
            
            if (result.affectedRows === 0) {
                throw new Error('User not found or no changes made');
            }
            
            // 返回更新后的用户信息
            return await this.findById(id);
        } catch (error) {
            throw new Error(`Failed to update user: ${error.message}`);
        }
    }

    // 删除用户
    async delete(id) {
        try {
            const result = await super.delete(this.tableName, id);
            
            return {
                success: result.affectedRows > 0,
                affectedRows: result.affectedRows
            };
        } catch (error) {
            throw new Error(`Failed to delete user: ${error.message}`);
        }
    }

    // 更新最后登录时间
    async updateLastLogin(id) {
        try {
            const query = `UPDATE users SET last_login_at = NOW() WHERE id = ?`;
            await this.pool.execute(query, [id]);
        } catch (error) {
            throw new Error(`Database update failed: ${error.message}`);
        }
    }

    // 软删除用户（更新状态为deleted）
    async softDelete(id) {
        try {
            const result = await super.softDelete(this.tableName, id, 'status', 'deleted');
            
            return {
                success: result.affectedRows > 0,
                affectedRows: result.affectedRows
            };
        } catch (error) {
            throw new Error(`Failed to soft delete user: ${error.message}`);
        }
    }

    // 批量更新用户状态
    async batchUpdateStatus(userIds, status) {
        try {
            const result = await super.batchUpdateStatus(this.tableName, userIds, status, 'status');
            
            return {
                success: result.affectedRows > 0,
                affectedRows: result.affectedRows,
                updatedIds: userIds.slice(0, result.affectedRows)
            };
        } catch (error) {
            throw new Error(`Failed to batch update user status: ${error.message}`);
        }
    }

    // 获取用户统计信息
    async getStats() {
        try {
            const query = `
                SELECT 
                    COUNT(*) as total_users,
                    SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active_users,
                    SUM(CASE WHEN status = 'inactive' THEN 1 ELSE 0 END) as inactive_users,
                    SUM(CASE WHEN role = 'admin' THEN 1 ELSE 0 END) as admin_users,
                    SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as new_today
                FROM users
            `;
            
            const [rows] = await this.pool.execute(query);
            return rows[0];
        } catch (error) {
            throw new Error(`Database stats query failed: ${error.message}`);
        }
    }

    // 关闭数据库连接池
    async close() {
        await super.close();
    }
}